// pages/cart/cart.js
import {getSetting,chooseAddress,openSetting} from "../../utils/wxAsync"
Page({
  data: {
    address:{},
    cart:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0
  },

  onShow () {
    const address = wx.getStorageSync('address')
    const cart = wx.getStorageSync('cart')||[]
    this.setData({
      address
    })
    this.setCart(cart)
  },
  //获取收货地址
  async handleChooseAddress(){
    try{
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting['scope.address']
      if(scopeAddress ===false){
        //打开权限设置的页面; ---让用户重新设置权限;
        await openSetting()
      }
      // 调用收货地址的api
      let address = await chooseAddress()
      console.log(address)
      address.all = address.provinceName+address.cityName+address.countyName+address.detailInfo;
      
      //存到缓存中
      wx.setStorageSync("address", address);
    }catch (error) {
      console.log(error);
    }
  },
  handeItemChange(e){
    // 先去获取被修改的商品的id
    const goods_id = e.currentTarget.dataset.id;
    //获取购物车数组;
    let {cart} = this.data;
    // 找到对应被修改的商品的对象;
    let index = cart.findIndex(v=>v.goods_id === goods_id);
    //选中状态取反
    cart[index].checked = !cart[index].checked;
    this.setCart(cart);  
  },
  setCart(cart){
    // 
    let allChecked  = true;
    // 总价格和总数量;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v=>{
        if(v.checked){
            totalPrice +=v.num*v.goods_price;
            totalNum += v.num;
        }else{
            allChecked=false;
        }
    })

    allChecked = cart.length!=0?allChecked:false;

    this.setData({
        cart,
        totalPrice,
        totalNum,
        allChecked
    })
    wx.setStorageSync("cart", cart);
  },
  handleItemAllCheck(){
    let {allChecked,cart} = this.data;

    allChecked = !allChecked

    cart.forEach(v=>v.checked = allChecked)

    this.setCart(cart)
  },
  handleItemNumSub(e){ //--
    let {id,operation} = e.currentTarget.dataset
    let {cart} = this.data;
    const index = cart.findIndex(v=>v.goods_id===id)
    if(cart[index].num>0){
      cart[index].num --
      this.setCart(cart);
      if(cart[index].num === 0 && operation === -1){
        cart.splice(index,1)
        this.setCart(cart)
      }
    }
    
  },
  handleItemNumAdd(e){ //++
    let {id} = e.currentTarget.dataset
    let {cart} = this.data;
    const index = cart.findIndex(v=>v.goods_id===id)
    cart[index].num++
    this.setCart(cart)
  },
  handlePay(){
    const {totalNum,address} = this.data;
    if(!address.userName){
      wx.showToast({
        title: '您还没有选择收货地址',
        icon: 'none'
      })
      return;
    }
    if(totalNum === 0){
      wx.showToast({
        title: '您还没有选择商品',
        icon: 'none'
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  }
})